﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using System.Collections;
using AAEngine.Engine;
using AAEngine.Engine.Core;
using AAEngine.Engine.Entities;
using AAEngine.Engine.Resources;

namespace AAEngine.Components.Basic
{
    /// <summary>
    /// Play sounds when events are triggered on an entity.
    /// </summary>
    public class EventSoundTrigger : EntityComponent
    {
        /// <summary>
        /// Sounds indexed by event type to trigger them.
        /// </summary>
        public Hashtable Events { get; set; }

        public SoundResource StartSound { get; set; }

        private bool _didSchedule;
        private bool _firedStartSound;

        public override void OnAdd()
        {
            IEventDispatcher ed = Owner.EventDispatcher;

            foreach (string key in Events.Keys)
            {
                ed.AddEventListener(key, SoundEventHandler);
            }

            if (!_firedStartSound && StartSound != null)
            {
                AAGame.SoundManager.Play(StartSound);
                _firedStartSound = true;
            }

            if (!_didSchedule)
            {
                AAGame.ProcessManager.Schedule(100, () => { OnReset(); });
                _didSchedule = true;
            }
        }

        public override void OnRemove()
        {
            IEventDispatcher ed = Owner.EventDispatcher;

            foreach (string key in Events.Keys)
            {
                ed.RemoveEventListener(key, SoundEventHandler);
            }
        }

        public override void OnReset()
        {
            if (Owner == null)
            {
                return;
            }

            OnRemove();
            OnAdd();
        }

        protected void SoundEventHandler(Event ev)
        {
            SoundResource sound = Events[ev.Type] as SoundResource;
            AAGame.SoundManager.Play(sound);
        }
    }
}
